import React, { useState, useRef, useEffect } from 'react';
import './BottomControls.css';

const BottomControls = ({ 
  audioSrc, 
  currentTime, 
  onTimeUpdate, 
  onSeek, 
  playbackRate, 
  onPlaybackRateChange,
  isPlaying, 
  onPlayPause, 
  isRepeating, 
  onRepeatToggle, 
  repeatStart, 
  repeatEnd 
}) => {
  const audioRef = useRef(null);
  const [duration, setDuration] = useState(0);
  const [loading, setLoading] = useState(false);
  const playbackRates = [0.5, 0.75, 1, 1.25, 1.5, 2];

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    const handleLoadedMetadata = () => {
      setDuration(audio.duration);
      setLoading(false);
    };

    const handleTimeUpdate = () => {
      if (onTimeUpdate) {
        onTimeUpdate(audio.currentTime);
      }
      
      // 处理重复播放
      if (isRepeating && repeatStart !== null && repeatEnd !== null) {
        if (audio.currentTime >= repeatEnd) {
          audio.currentTime = repeatStart;
        }
      }
    };

    const handleLoadStart = () => setLoading(true);
    const handleCanPlay = () => setLoading(false);

    audio.addEventListener('loadedmetadata', handleLoadedMetadata);
    audio.addEventListener('timeupdate', handleTimeUpdate);
    audio.addEventListener('loadstart', handleLoadStart);
    audio.addEventListener('canplay', handleCanPlay);

    return () => {
      audio.removeEventListener('loadedmetadata', handleLoadedMetadata);
      audio.removeEventListener('timeupdate', handleTimeUpdate);
      audio.removeEventListener('loadstart', handleLoadStart);
      audio.removeEventListener('canplay', handleCanPlay);
    };
  }, [onTimeUpdate, isRepeating, repeatStart, repeatEnd]);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    if (Math.abs(audio.currentTime - currentTime) > 0.5) {
      audio.currentTime = currentTime;
    }
  }, [currentTime]);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    audio.playbackRate = playbackRate;
  }, [playbackRate]);

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    if (isPlaying) {
      const playPromise = audio.play();
      if (playPromise !== undefined) {
        playPromise.catch(error => {
          console.error('音频播放失败:', error);
          if (error.name === 'NotAllowedError') {
            console.warn('Safari需要用户交互才能播放音频');
            if (onPlayPause) {
              onPlayPause();
            }
          }
        });
      }
    } else {
      audio.pause();
    }
  }, [isPlaying, onPlayPause]);

  const handleProgressClick = (e) => {
    const progressBar = e.currentTarget;
    const clickX = e.nativeEvent.offsetX;
    const width = progressBar.offsetWidth;
    const newTime = (clickX / width) * duration;
    
    if (onSeek) {
      onSeek(newTime);
    }
  };

  const handleRateChange = (rate) => {
    if (onPlaybackRateChange) {
      onPlaybackRateChange(rate);
    }
  };

  const formatTime = (time) => {
    if (!time || isNaN(time)) return '00:00';
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  };

  return (
    <div className="bottom-controls">
      <audio ref={audioRef} src={audioSrc} />
      
      {/* 进度条区域 */}
      <div className="progress-section">
        <div className="progress-info">
          <span className="time-display">{formatTime(currentTime)}</span>
          <span className="time-display">{formatTime(duration)}</span>
        </div>
        <div className="progress-bar" onClick={handleProgressClick}>
          <div className="progress-track">
            <div 
              className="progress-fill" 
              style={{ width: `${duration > 0 ? (currentTime / duration) * 100 : 0}%` }}
            />
            {isRepeating && repeatStart !== null && repeatEnd !== null && (
              <>
                <div 
                  className="repeat-start" 
                  style={{ left: `${(repeatStart / duration) * 100}%` }}
                />
                <div 
                  className="repeat-end" 
                  style={{ left: `${(repeatEnd / duration) * 100}%` }}
                />
                <div 
                  className="repeat-range" 
                  style={{ 
                    left: `${(repeatStart / duration) * 100}%`,
                    width: `${((repeatEnd - repeatStart) / duration) * 100}%`
                  }}
                />
              </>
            )}
          </div>
        </div>
      </div>

      {/* 控制按钮区域 */}
      <div className="controls-section">
        {/* 播放控制 */}
        <div className="play-controls">
          <button 
            className={`control-btn play-btn ${isPlaying ? 'playing' : ''}`}
            onClick={onPlayPause}
            disabled={!audioSrc || loading}
          >
            {loading ? '⏳' : (isPlaying ? '⏸️' : '▶️')}
          </button>
          
          <button 
            className={`control-btn repeat-btn ${isRepeating ? 'active' : ''}`}
            onClick={onRepeatToggle}
            disabled={!audioSrc}
            title="重复播放"
          >
            🔁
          </button>
        </div>

        {/* 播放速度控制 */}
        <div className="speed-controls">
          <span className="speed-label">速度</span>
          <div className="speed-buttons">
            {playbackRates.map(rate => (
              <button
                key={rate}
                className={`speed-btn ${playbackRate === rate ? 'active' : ''}`}
                onClick={() => handleRateChange(rate)}
                disabled={!audioSrc}
              >
                {rate === 1 ? '1×' : `${rate}×`}
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default BottomControls;